package com.sh.data.engine.domain.shims.sql.builder;

import com.sh.data.engine.domain.base.model.enums.Database;
import com.sh.data.engine.domain.shims.sql.Context;
import com.sh.data.engine.domain.shims.sql.delete.Delete;
import com.sh.data.engine.domain.shims.sql.insert.Insert;
import com.sh.data.engine.domain.shims.sql.insert.InsertSql;
import com.sh.data.engine.domain.shims.sql.select.Select;
import com.sh.data.engine.domain.shims.sql.select.SelectSql;
import com.sh.data.engine.domain.shims.sql.update.Update;
import lombok.extern.slf4j.Slf4j;

import javax.sql.DataSource;
import java.io.Closeable;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author: mengzheng.mhc
 * @date: 2024/6/5 15:17
 */
@Slf4j
public class QueryBuilder implements Closeable {

    private final Context context;

    public QueryBuilder(Database database, DataSource dataSource) throws SQLException {
        this(database, dataSource.getConnection());
    }

    public QueryBuilder(Database database, Connection connection) {
        this.context = new Context(database, connection);
    }

    public QueryBuilder reset() {
        this.context.reset();
        return this;
    }

    public Select select() {
        reset();
        return new Select(context);
    }

    public SelectSql selectSql(String sql) {
        reset();
        return new SelectSql(context, sql);
    }

    public Update update() {
        return new Update(context);
    }

    public Update update(String table) {
        return new Update(context, table);
    }

    public Delete delete() {
        return new Delete(context);
    }

    public Delete delete(String table) {
        return new Delete(context, table);
    }

    public Insert insert() {
        return new Insert(context);
    }

    public Insert insert(String table) {
        return new Insert(context, table);
    }

    public InsertSql insertSql(String sql) {
        return new InsertSql(context, sql);
    }

    @Override
    public void close() {
        try {
            this.context.reset();
            this.context.colseConnection();
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
        }
    }

    @Override
    public String toString() {
        return context.toString();
    }
}
